/*
 * MIT License
 *
 * Copyright (c) 2025 Mark·虎
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

package com.hsxxherp.key.uia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hsxxherp.key.uia.entity.SysApplication;
import com.hsxxherp.key.uia.entity.SysApplicationGroup;
import com.hsxxherp.key.uia.entity.SysApplicationVersion;
import com.hsxxherp.key.uia.mapper.SysApplicationGroupMapper;
import com.hsxxherp.key.uia.mapper.SysApplicationMapper;
import com.hsxxherp.key.uia.service.ISysAppParameterTemplateService;
import com.hsxxherp.key.uia.service.ISysApplicationService;
import com.hsxxherp.key.uia.service.ISysApplicationVersionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

/**
 * 应用服务实现
 *
 * @author Mark·虎（2486970363@qq.com）
 */
@Service
public class SysApplicationServiceImpl extends ServiceImpl<SysApplicationMapper, SysApplication> implements ISysApplicationService {

    private static final Logger logger = LoggerFactory.getLogger(SysApplicationServiceImpl.class);

    @Autowired
    private SysApplicationGroupMapper sysApplicationGroupMapper;

    @Autowired
    private ISysApplicationVersionService sysApplicationVersionService;

    @Autowired
    private ISysAppParameterTemplateService sysAppParameterTemplateService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysApplication insertOrCreateApplication(SysApplication sysApplication) {
        // 检查是否有相同名称的 app_name
        QueryWrapper<SysApplication> nameQueryWrapper = new QueryWrapper<>();
        nameQueryWrapper.eq("app_name", sysApplication.getAppName());
        if (count(nameQueryWrapper) > 0) {
            throw new RuntimeException("应用名称已存在，无法添加");
        }

        // 检查 group_id 是否存在
        String groupId = sysApplication.getGroupId();
        if (groupId != null) {
            SysApplicationGroup group = sysApplicationGroupMapper.selectById(groupId);
            if (group == null) {
                throw new RuntimeException("关联的应用分组 ID 不存在，无法添加");
            }
        }

        // 若检查通过，则调用父类的 save 方法进行保存
        boolean success = super.save(sysApplication);
        if (success) {
            // 创建默认版本
            SysApplicationVersion version = new SysApplicationVersion();
            version.setVersionId(UUID.randomUUID().toString());
            version.setAppId(sysApplication.getAppId());
            version.setVersionNum("1.0.0"); // 默认版本号
            version.setDescription("初始版本");

            // 调用版本服务创建版本
            sysApplicationVersionService.createVersion(version);

            // 创建默认的应用配置模板
            sysAppParameterTemplateService.createDefaultTemplate(sysApplication.getAppId());

            return sysApplication;
        }
        return null;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public SysApplication updateApplication(SysApplication sysApplication) {
        // 检查要修改的应用是否存在
        SysApplication existingApplication = getById(sysApplication.getAppId());
        if (existingApplication == null) {
            logger.error("要修改的应用不存在，应用 ID: {}", sysApplication.getAppId());
            throw new RuntimeException("要修改的应用不存在");
        }

        // 检查修改后的应用名称是否重复（排除当前要修改的应用）
        QueryWrapper<SysApplication> nameQueryWrapper = new QueryWrapper<>();
        nameQueryWrapper.eq("app_name", sysApplication.getAppName())
                .ne("app_id", sysApplication.getAppId());
        if (count(nameQueryWrapper) > 0) {
            logger.error("应用名称已存在，无法修改，名称: {}", sysApplication.getAppName());
            throw new RuntimeException("应用名称已存在，无法修改");
        }

        // 检查 group_id 是否存在
        String groupId = sysApplication.getGroupId();
        if (groupId != null) {
            SysApplicationGroup group = sysApplicationGroupMapper.selectById(groupId);
            if (group == null) {
                logger.error("关联的应用分组 ID 不存在，无法修改，分组 ID: {}", groupId);
                throw new RuntimeException("关联的应用分组 ID 不存在，无法修改");
            }
        }

        // 处理应用图标
        if (sysApplication.getAppIcon() != null) {
            existingApplication.setAppIcon(sysApplication.getAppIcon());
        }

        // 执行更新操作
        boolean success = updateById(existingApplication);
        if (success) {
            // 更新成功后，重新查询获取最新数据
            return getById(sysApplication.getAppId());
        }
        logger.error("应用修改失败，应用 ID: {}", sysApplication.getAppId());
        return null;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteApplication(String appId) {
        // 检查要删除的应用是否存在
        SysApplication existingApplication = getById(appId);
        if (existingApplication == null) {
            logger.error("要删除的应用不存在，应用 ID: {}", appId);
            throw new RuntimeException("要删除的应用不存在");
        }

        // 执行软删除操作
        boolean success = removeById(appId);
        if (success) {
            logger.info("应用删除成功，应用 ID: {}", appId);
        } else {
            logger.error("应用删除失败，应用 ID: {}", appId);
        }
        return success;
    }
}